$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/dctnrs/list',
        datatype: "json",
        colModel: [			
			{ label: 'ID', name: 'id_', width: 45, key: true,hidden:true },
			{ label: '所属组织', name: 'deptName', width: 75 },
			{ label: '姓名', name: 'name', width: 50 },
			{ label: '工号', name: 'jobNO', width: 75 },
			{ label: '卡号', name: 'cardNO', width: 75 },
			{ label: '身份证号码', name: 'ICNO', width: 75 },
			{ label: '手机号', name: 'mobileNO', width: 75 },
			{ label: '类型', name: 'type', width: 50 ,formatter: function(value, options, row){
				return value === 0 ? 
						'<span >护士</span>' : 
						'<span >医生</span>';
			}},
			{ label: '状态', name: 'status', width: 50, formatter: function(value, options, row){
				return value === 0 ? 
						'<span class="label label-danger">禁用</span>' : 
						'<span class="label label-success">正常</span>';
			}},
        	{ label: '时间', name: 'updateTime', width: 90 }
        ],
		viewrecords: true,
        
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
});

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    }
};
var ztree;
/**
 * 展开树
 * @param treeId  
 */
function expand_ztree(treeId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    treeObj.expandAll(true);
}

/**
 * 收起树：只展开根节点下的一级节点
 * @param treeId
 */
function close_ztree(treeId){
    var treeObj = $.fn.zTree.getZTreeObj(treeId);
    var nodes = treeObj.transformToArray(treeObj.getNodes());
    var nodeLength = nodes.length;
    for (var i = 0; i < nodeLength; i++) {
        if (nodes[i].id == '0') {
            //根节点：展开
            treeObj.expandNode(nodes[i], true, true, false);
        } else {
            //非根节点：收起
            treeObj.expandNode(nodes[i], false, true, false);
        }
    }
}

/**
 * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
 * @param treeId
 * @param searchConditionId 文本框的id
 */
function search_ztree(treeId, searchConditionId){
	searchByFlag_ztree(treeId, searchConditionId, "");
}

/**
 * 搜索树，高亮显示并展示【模糊匹配搜索条件的节点s】
 * @param treeId
 * @param searchConditionId		搜索条件Id
 * @param flag 					需要高亮显示的节点标识
 */
function searchByFlag_ztree(treeId, searchConditionId, flag){
	//<1>.搜索条件
	var searchCondition = $('#' + searchConditionId).val();
	//<2>.得到模糊匹配搜索条件的节点数组集合
	var highlightNodes = new Array();
	if (searchCondition != "") {
		var treeObj = $.fn.zTree.getZTreeObj(treeId);
		highlightNodes = treeObj.getNodesByParamFuzzy("name", searchCondition, null);
	}
	//<3>.高亮显示并展示【指定节点s】
	highlightAndExpand_ztree(treeId, highlightNodes, flag);
}

/**
 * 高亮显示并展示【指定节点s】
 * @param treeId
 * @param highlightNodes 需要高亮显示的节点数组
 * @param flag			 需要高亮显示的节点标识
 */
function highlightAndExpand_ztree(treeId, highlightNodes, flag){
	var treeObj = $.fn.zTree.getZTreeObj(treeId);
	//<1>. 先把全部节点更新为普通样式
	var treeNodes = treeObj.transformToArray(treeObj.getNodes());
	for (var i = 0; i < treeNodes.length; i++) {
		treeNodes[i].highlight = false;
		treeObj.updateNode(treeNodes[i]);
	}
	//<2>.收起树, 只展开根节点下的一级节点
	close_ztree(treeId);
	//<3>.把指定节点的样式更新为高亮显示，并展开
	if (highlightNodes != null) {
		for (var i = 0; i < highlightNodes.length; i++) {
			if (flag != null && flag != "") {
				if (highlightNodes[i].flag == flag) {
					//高亮显示节点，并展开
					highlightNodes[i].highlight = true;
					treeObj.updateNode(highlightNodes[i]);
					//高亮显示节点的父节点的父节点....直到根节点，并展示
					var parentNode = highlightNodes[i].getParentNode();
					var parentNodes = getParentNodes_ztree(treeId, parentNode);
					treeObj.expandNode(parentNodes, true, false, true);
					treeObj.expandNode(parentNode, true, false, true);
				}
			} else {
				//高亮显示节点，并展开
				highlightNodes[i].highlight = true;
				treeObj.updateNode(highlightNodes[i]);
				//高亮显示节点的父节点的父节点....直到根节点，并展示
				var parentNode = highlightNodes[i].getParentNode();
				var parentNodes = getParentNodes_ztree(treeId, parentNode);
				treeObj.expandNode(parentNodes, true, false, true);
				treeObj.expandNode(parentNode, true, false, true);
			}
		}
	}
}

/**
 * 递归得到指定节点的父节点的父节点....直到根节点
 */
function getParentNodes_ztree(treeId, node){
	if (node != null) {
		var treeObj = $.fn.zTree.getZTreeObj(treeId);
		var parentNode = node.getParentNode();
		return getParentNodes_ztree(treeId, parentNode);
	} else {
		return node;
	}
}

/**
 * 设置树节点字体样式
 */
function setFontCss_ztree(treeId, treeNode) {
	if (treeNode.id == 0) {
		//根节点
		return {color:"#333", "font-weight":"bold"};
	} else if (treeNode.isParent == false){
		//叶子节点
		return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#660099", "font-weight":"normal"};
	} else {
		//父节点
		return (!!treeNode.highlight) ? {color:"#ff0000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
	}
}
var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
			cardNO: null
		},
		showList: true,
		title:null,
		dctnrs:{
			
		}
	},
	methods: {
		query: function () {
			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.roleList = {};
			vm.dctnrs = {deptName:null, deptId:null, status:1};

			vm.getDept();
		},
        getDept: function(){
            //加载组织树
            $.get(baseURL + "sys/dept/list", function(r){
                ztree = $.fn.zTree.init($("#deptTree"), setting, r);
                var node = ztree.getNodeByParam("deptId", vm.dctnrs.deptId);
                if(node != null){
                    ztree.selectNode(node);
                    vm.dctnrs.deptName = node.name;
				}
            })
        },
		update: function () {
			var userId = getSelectedRow();
			if(userId == null){
				return ;
			}
			
			vm.showList = false;
            vm.title = "修改";
           
			vm.getDctnrs(userId);
		},
		del: function () {
			var userIds = getSelectedRows();
			if(userIds == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/dctnrs/delete",
                    contentType: "application/json",
				    data: JSON.stringify(userIds),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(){
                                vm.reload();
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		saveOrUpdate: function () {
			var url = vm.dctnrs.id_ == null ? "sys/dctnrs/save" : "sys/dctnrs/update";
			$.ajax({
				type: "POST",
			    url: baseURL + url,
                contentType: "application/json",
			    data: JSON.stringify(vm.dctnrs),
			    success: function(r){
			    	if(r.code === 0){
						alert('操作成功', function(){
							vm.reload();
						});
					}else{
						alert(r.msg);
					}
				}
			});
		},
		getDctnrs: function(userId){
			$.get(baseURL + "sys/dctnrs/info/"+userId, function(r){
				console.log(r);
				vm.dctnrs = r.dctnrs;
				vm.dctnrs.passWord = null;

                vm.getDept();
			});
		},
        deptTree: function(){
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择组织",
                area: ['300px', '450px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级组织
                    vm.dctnrs.deptId = node[0].deptId;
                    vm.dctnrs.deptName = node[0].name;

                    layer.close(index);
                }
            });
        },
		reload: function () {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{ 
                postData:{'cardNO': vm.q.cardNO},
                page:page
            }).trigger("reloadGrid");
		}
	}
});